package site.wetsion.galio.sdk.strategy;

import com.alibaba.fastjson.JSONObject;
import org.springframework.util.StringUtils;
import site.wetsion.galio.sdk.common.GalioOauthConstant;
import java.util.concurrent.ConcurrentHashMap;

/**
 * 间隔一段时间，再去auth校验token
 *
 * @author wetsion
 * @version 1.0
 * @CLassName IntervalTokenCheckStrategy
 * @date 2019/4/12 5:03 PM
 */
public class IntervalTokenCheckStrategy extends AbstractTokenCheckStrategy {

    private static final ConcurrentHashMap<String, Long> TOKEN_MAP = new ConcurrentHashMap<>();

    /** interval time, default 30 * 60 * 1000 milliseconds **/
    private Long interval = 30 * 60 * 1000L;

    @Override
    public synchronized JSONObject checkToken(String token) {
        JSONObject result = null;
        if (StringUtils.isEmpty(token)) {
            result = new JSONObject();
            result.put(GalioOauthConstant.ACTIVE, false);
            result.put("message", "token can not be null!");
        } else {
            if (!TOKEN_MAP.containsKey(token)) {
                TOKEN_MAP.put(token, System.currentTimeMillis());
                result = new JSONObject();
                result.put(GalioOauthConstant.ACTIVE, true);
            } else {
                Long lastTime = TOKEN_MAP.get(token);
                if ((System.currentTimeMillis() - lastTime) < interval) {
                    // 小于间隔时间，不再去auth校验，返回active通过
                    result = new JSONObject();
                    result.put(GalioOauthConstant.ACTIVE, true);
                } else {
                    // 大于设定间隔时间，需要再去auth校验token
                    result = remoteCheckToken(token);
                }
            }
        }
        return result;
    }

    /** 自定义间隔时间 **/
    public void setInterval(Long interval) {
        this.interval = interval;
    }
}
